package iamutkarshtiwari.github.io.ananas.editimage.fragment.crop;

import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.adapter.CropProvider;
import iamutkarshtiwari.github.io.ananas.editimage.utils.MyToast;
import iamutkarshtiwari.github.io.ananas.editimage.view.CropImageView;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageInfo;

import java.io.IOException;
import java.util.ArrayList;

public class CropFragment extends ComponentContainer {
    PageSlider pageSlider;
    private CropProvider itemProvider;
//    private int lastPosition = 0;
    private CropImageView cropPanel;
    private EditImageAbility editImageAbility;
    //    private OnLoadingDialogListener loadingDialogListener;
    private CompositeDisposable disposables = new CompositeDisposable();
    private ListContainer ratioList;
    private ArrayList<String> items;
    //    ListContainer ratioList;

    /**
     * 构造
     *
     * @param context    Context对象
     * @param pageSlider PageSlider对象
     */
    public CropFragment(Context context, PageSlider pageSlider) {
        super(context);
        this.pageSlider = pageSlider;
        editImageAbility = (EditImageAbility) context;
        cropPanel = editImageAbility.cropPanel;
        initView();
    }

    private void initView() {
        Component component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_fragment_crop_layout, null, false);
        addComponent(component);

        //返回
        findComponentById(ResourceTable.Id_back_to_main).setClickedListener(component1 -> backToMain());
        ratioList = (ListContainer) findComponentById(ResourceTable.Id_ratio_list_group);
        ratioList.setOrientation(Component.HORIZONTAL);
        setUpRatioList();
    }

    /**
     * 显示自定义视图
     */
    public void onShow() {
        editImageAbility.mode = EditImageAbility.MODE_CROP;
        cropPanel.setImageBitmap(editImageAbility.getMainBit(), editImageAbility.getBitmapRect());
        cropPanel.setVisibility(Component.VISIBLE);
        cropPanel.setFixedAspectRatio(false);
        //刷新位置
        itemProvider = new CropProvider(mContext, this, items);
        ratioList.setItemProvider(itemProvider);
    }


    /**
     * 返回主视图
     */
    public void backToMain() {
        editImageAbility.mode = EditImageAbility.MODE_NONE;
        cropPanel.setVisibility(Component.HIDE);
        itemProvider.setLastPoisition(0);
        itemProvider.reset();
        pageSlider.setCurrentPage(0,false);
        pageSlider.setVisibility(Component.HIDE);
        onDestroy();
        editImageAbility.saveOrApply(false);
    }

    private void setUpRatioList() {
//        ratioList.removeAllComponents();
//        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
//
        RatioText[] ratioTextList = RatioText.values();
        items = new ArrayList();
        for (RatioText ratioText : ratioTextList) {
            try {
                items.add(getResourceManager().getElement(ratioText.getRatioTextId()).getString());
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
            }
//            Text text = new Text(mContext);
//            toggleButtonStatus(text, false);
//            text.setTextSize(15);
//            text.setMarginLeft(20);
//            text.setMarginRight(20);
//            text.setTextAlignment(TextAlignment.CENTER);
////            text.setText(ratioTextList[i].getRatioTextId());
//            ratioList.addComponent(text, config);
//
//            if (i == 0) {
//                selectedTextView = text;
//            }
//
//            text.setTag(ratioTextList[i]);
////            text.setOnClickListener(cropRatioClick);
        }
//        toggleButtonStatus(selectedTextView, true);
    }

    /**
     * cropItem点击事件
     *
     * @param position 位置
     */
    public void clickedCropItem(int position) {
        itemProvider.setLastPoisition(position);
//        itemProvider.notifyDataChanged();

        RatioText ratioText = RatioText.values()[position];
        if (ratioText == RatioText.FREE) {
            cropPanel.setFixedAspectRatio(false);
        } else if (ratioText == RatioText.FIT_IMAGE) {
            PixelMap currentBmp = editImageAbility.getMainBit();
            ImageInfo info = currentBmp.getImageInfo();
            cropPanel.setAspectRatio(info.size.width, info.size.height);
        } else {
            AspectRatio aspectRatio = ratioText.getAspectRatio();
            cropPanel.setAspectRatio(aspectRatio.getAspectX(), aspectRatio.getAspectY());
        }
    }

    /**
     * 应用修改
     */
    public void applyCropImage() {
        disposables.add(getCroppedBitmap()
//                .subscribeOn(Schedulers.mainThread())
//                .observeOn(Schedulers.mainThread())
//                .doOnSubscribe(subscriber -> loadingDialogListener.showLoadingDialog())
//                .doFinally(() -> loadingDialogListener.dismissLoadingDialog())
                .subscribe(bitmap -> {
                    editImageAbility.changeMainBitmap(bitmap, true);
                    backToMain();
                }, e -> {
                    e.printStackTrace();
                    backToMain();
                    MyToast.show(getContext(), "Error while saving image");
                }));
    }

    private Single<PixelMap> getCroppedBitmap() {
        return Single.fromCallable(() -> cropPanel.getCroppedImage(editImageAbility.getImageViewMatrix()));
    }

    //    @Override
    public void onDestroy() {
        disposables.dispose();
//        super.onDestroy();
    }

}
